// noinspection ExceptionCaughtLocallyJS
export class AppController {
    constructor(dataService, uiController) {
        this.dataService = dataService;
        this.uiController = uiController;
        this.rankData = null;
        this.matchingChart = null;
    }

    init() {
        this.bindEvents();
        this.loadInitialData();
        this.initMatchingRateChart();
    }

    bindEvents() {
        // 监听复选框变化
        document.querySelectorAll('.form-check-input').forEach(checkbox => {
            checkbox.addEventListener('change', () => this.uiController.updateVisibility());
        });
        
        // 为组织分析详情添加点击事件
        const apiTotalStat = document.querySelector('#api-total-stat');
        if (apiTotalStat) {
            apiTotalStat.addEventListener('click', async (e) => {
                e.preventDefault();
                await this.loadApiData();
            });
        }

        // 为数据库人员信息添加点击事件
        const dbTotalStat = document.querySelector('#db-total-stat');
        if (dbTotalStat) {
            dbTotalStat.addEventListener('click', async (e) => {
                e.preventDefault();
                const modal = this.uiController.showModal('数据库人员信息');
                try {
                    const result = await this.dataService.getDbData();
                    if (result.error) {
                        throw new Error(result.error);
                    }
                    this.uiController.displayTableData(result.data);
                } catch (error) {
                    console.error('加载数据库数据失败:', error);
                }
            });
        }
        
        // 监听序列筛选
        const seriesFilter = document.querySelector('#series-filter');
        if (seriesFilter) {
            seriesFilter.addEventListener('change', (e) => {
                this.displayRankData(e.target.value);
            });
        }
    }

    async loadInitialData() {
        try {
            // 显示加载状态
            this.uiController.showLoadingSpinner(
                this.uiController.getElement(this.uiController.elements.totalComparison)
            );

            // 并行加载所有数据
            const [totalResult, ageResult, rankResult, matchRateResult] = await Promise.all([
                this.dataService.getTotalComparison(),
                this.dataService.getAgeComparison(),
                this.dataService.getRankComparison(),
                this.dataService.getMatchRate()
            ]);

            // 保存职级数据用于后续筛选
            this.rankData = rankResult;

            // 合并数据，确保正确处理数字类型
            const combinedData = {
                api_total: parseInt(totalResult.data.api_total) || 0,
                db_total: parseInt(totalResult.data.db_total) || 0,
                matched: totalResult.data.matched,
                api_avg_age: parseFloat(ageResult.data.api_avg_age) || 0,
                db_avg_age: parseFloat(ageResult.data.db_avg_age) || 0,
                difference: parseFloat(ageResult.data.difference) || 0,
                age_matched: Math.abs(parseFloat(ageResult.data.api_avg_age) - parseFloat(ageResult.data.db_avg_age)) <= 0.1,
                rank_data: {
                    api_data: rankResult.data?.api_data || {},
                    db_data: rankResult.data?.db_data || {},
                    comparison: rankResult.data?.comparison || {}
                },
                match_rate: matchRateResult.data || { rate: 81.5, matched: 22, total: 27 }
            };
            
            // 更新UI显示
            this.uiController.updateTotalComparison(combinedData);
            this.uiController.updateRankComparison(rankResult, 'P序列');
            
            // 更新匹配率显示
            this.updateMatchRate(combinedData.match_rate);
            
        } catch (error) {
            console.error('加载数据失败:', error);
            this.uiController.showError('加载数据失败: ' + error.message);
        }
    }

    async loadRankData() {
        try {
            const data = await this.dataService.getRankComparison();
            this.rankData = data;
            this.uiController.updateRankComparison(data);
            return data;  // 返回数据
        } catch (error) {
            console.error('加载职级分布数据失败:', error);
            this.uiController.updateRankComparison({ error: '加载数据失败' });
            return null;
        }
    }

    displayRankData(series) {
        if (this.rankData && this.rankData.data) {
            this.uiController.updateRankComparison(this.rankData, series);
        } else {
            // 如果没有数据，重新加载
            this.loadRankData().then(data => {
                if (data && data.data) {
                    this.uiController.updateRankComparison(data, series);
                }
            });
        }
    }

    async loadDbTableData() {
        const modal = this.uiController.showModal(`
            <i class="fas fa-database me-2"></i>
            数据库表数据 (per_main)
        `);
        
        // 确保显示表格容器
        this.uiController.showTableContainer();
        
        try {
            const data = await this.dataService.getDbData();
            if (data.data && data.data.length > 0) {
                // 定义字段顺序
                const preferredOrder = [
                    'name',      // 姓名
                    'id',        // ID
                    'level',     // 职级
                    'gender',    // 性别
                ];
                
                // 重新排序数据中的字段
                const formattedData = {
                    data: data.data.map(row => {
                        const orderedRow = {};
                        // 先添加优先字段
                        preferredOrder.forEach(field => {
                            if (field in row) {
                                orderedRow[field] = row[field];
                            }
                        });
                        // 再添加其他字段
                        Object.keys(row).forEach(field => {
                            if (!preferredOrder.includes(field)) {
                                orderedRow[field] = row[field];
                            }
                        });
                        return orderedRow;
                    })
                };
                
                this.uiController.updateModalContent(formattedData);
            } else {
                this.uiController.updateModalContent(data);
            }
        } catch (error) {
            console.error('加载数据库数据失败:', error);
            this.uiController.updateModalContent({ error: '加载数据失败' });
        }
    }

    async loadApiData() {
        try {
            // 显示模态窗口
            const modalElement = document.getElementById('dbDataModal');
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
            
            // 获取容器元素
            const iframeContainer = this.uiController.getElement('#iframe-container');
            const tableContainer = this.uiController.getElement('#table-container');
            const iframe = this.uiController.getElement('#external-page');
            
            if (!iframeContainer || !tableContainer || !iframe) {
                throw new Error('找不到必要的DOM元素');
            }

            // 隐藏表格容器，显示iframe容器
            tableContainer.style.display = 'none';
            iframeContainer.style.display = 'block';

            // 直接加载登录页面
            iframe.src = 'https://test-tds-standard.cepin.com/#/login';

            // 监听iframe加载完成事件
            iframe.onload = () => {
                // 等待一段时间确保页面完全加载
                setTimeout(() => {
                    try {
                        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        
                        // 使用XPath定位元素
                        const getElementByXPath = (xpath) => {
                            return document.evaluate(xpath, iframeDoc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                        };

                        // 定位用户名输入框
                        const usernameInput = getElementByXPath("//input[@placeholder='账号']");
                        const passwordInput = getElementByXPath("//input[@placeholder='密码']");
                        const loginButton = getElementByXPath("//button[contains(text(), '登录')]");

                        if (usernameInput && passwordInput && loginButton) {
                            // 填充登录信息
                            usernameInput.value = 'admin';
                            passwordInput.value = '123456';

                            // 触发Vue的input和change事件
                            ['input', 'change'].forEach(event => {
                                const evt = new Event(event, { bubbles: true });
                                usernameInput.dispatchEvent(evt);
                                passwordInput.dispatchEvent(evt);
                            });

                            // 点击登录按钮
                            loginButton.click();
                            
                            // 等待登录完成后跳转
                            setTimeout(() => {
                                iframe.src = 'https://test-tds-standard.cepin.com/tds/#/tissue-analysis/portrait';
                            }, 2000);
                        }
                    } catch (error) {
                        console.error('登录过程中发生错误:', error);
                    }
                }, 3000);
            };
            
        } catch (error) {
            console.error('加载组织分析详情失败:', error);
            this.uiController.showError('加载组织分析详情失败: ' + error.message);
            
            // 恢复表格容器显示
            const tableContainer = this.uiController.getElement('#table-container');
            const iframeContainer = this.uiController.getElement('#iframe-container');
            if (tableContainer && iframeContainer) {
                tableContainer.style.display = 'block';
                iframeContainer.style.display = 'none';
            }
        }
    }

    _generateOverviewTable(data) {
        if (!data) return '<div class="text-center">暂无数据</div>';
        return `
            <div class="table-responsive">
                <table class="table table-bordered">
                    <tbody>
                        ${Object.entries(data).map(([key, value]) => `
                            <tr>
                                <td class="fw-bold">${key}</td>
                                <td>${value}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    _generateEfficiencyTable(data) {
        if (!data) return '<div class="text-center">暂无数据</div>';
        return `
            <div class="table-responsive">
                <table class="table table-bordered">
                    <tbody>
                        ${Object.entries(data).map(([key, value]) => `
                            <tr>
                                <td class="fw-bold">${key}</td>
                                <td>${value}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    _generatePerformanceTable(data) {
        if (!data) return '<div class="text-center">暂无数据</div>';
        return `
            <div class="table-responsive">
                <table class="table table-bordered">
                    <tbody>
                        ${Object.entries(data).map(([key, value]) => `
                            <tr>
                                <td class="fw-bold">${key}</td>
                                <td>${value}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    _generateCustomerTable(data) {
        if (!data) return '<div class="text-center">暂无数据</div>';
        return `
            <div class="table-responsive">
                <table class="table table-bordered">
                    <tbody>
                        ${Object.entries(data).map(([key, value]) => `
                            <tr>
                                <td class="fw-bold">${key}</td>
                                <td>${value}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    initMatchingRateChart() {
        const chartDom = document.getElementById('matching-rate-chart');
        if (!chartDom) return;
        
        this.matchingChart = echarts.init(chartDom);
        
        const option = {
            title: {
                show: false  // 隐藏标题
            },
            series: [
                {
                    type: 'gauge',
                    startAngle: 180,
                    endAngle: 0,
                    min: 0,
                    max: 100,
                    splitNumber: 5,
                    radius: '80%',
                    center: ['50%', '60%'],  // 稍微上移整个图表
                    itemStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 1,
                            y2: 0,
                            colorStops: [{
                                offset: 0,
                                color: '#40a9ff'
                            }, {
                                offset: 1,
                                color: '#1890ff'
                            }]
                        }
                    },
                    progress: {
                        show: true,
                        roundCap: true,
                        width: 8
                    },
                    pointer: {
                        show: false
                    },
                    axisLine: {
                        roundCap: true,
                        lineStyle: {
                            width: 8,
                            color: [
                                [0, {
                                    type: 'linear',
                                    x: 0,
                                    y: 0,
                                    x2: 1,
                                    y2: 0,
                                    colorStops: [{
                                        offset: 0,
                                        color: '#40a9ff'
                                    }, {
                                        offset: 1,
                                        color: '#1890ff'
                                    }]
                                }],
                                [1, '#f0f0f0']
                            ]
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: false
                    },
                    axisLabel: {
                        show: false
                    },
                    detail: {
                        show: true,
                        fontSize: 28,
                        fontWeight: 'bold',
                        offsetCenter: [0, '-10%'],
                        formatter: '{value}%',
                        color: '#1890ff',
                        valueAnimation: true
                    },
                    data: [{
                        value: 0,
                        name: '匹配率'
                    }]
                }
            ]
        };

        this.matchingChart.setOption(option);
        
        window.addEventListener('resize', () => {
            this.matchingChart && this.matchingChart.resize();
        });
    }

    updateMatchRate(matchRate) {
        if (!matchRate) return;

        // 更新右侧面板的匹配率显示
        const matchRateValue = document.querySelector('.match-rate-value');
        const matchRateDetail = document.querySelector('.match-rate-detail span');
        if (matchRateValue) {
            matchRateValue.textContent = `${matchRate.rate}%`;
        }
        if (matchRateDetail) {
            matchRateDetail.textContent = `${matchRate.matched}/${matchRate.total}项匹配`;
        }

        // 更新图表的匹配率显示
        if (this.matchingChart) {
            const option = this.matchingChart.getOption();
            
            // 更新进度条颜色范围
            option.series[0].axisLine.lineStyle.color[0][0] = matchRate.rate / 100;
            
            // 更新数值
            option.series[0].data[0].value = matchRate.rate;
            
            this.matchingChart.setOption(option);
        }
    }
} 